<template>
  <div class="meterage-manage">
    <div class="model-title-css">投资进度汇总表</div>
    <div class="background_wrap">
      <div class="operate_wrap flex">
        <div class="flex-right">
          <el-date-picker v-model="search.year" type="year" size="small" :clearable="false" @change="getList()" value-format="yyyy" placeholder="选择年">
          </el-date-picker>
          <!-- <el-button style="margin-left: 15px" type="primary" size="small" class="add buildButtonStyle" @click="writeReport" v-permission="permission.add"><i class="iconfont icon-icon_add"></i> 新增
          </el-button> -->
          <el-button class="search buildButtonStyle" size="small" @click="priviewReport()">预览报表</el-button>
          <el-button class="search buildButtonStyle" size="small" @click="exportByDate()">导出报表</el-button>
        </div>
      </div>

      <!--======================================================================================================-->
      <!--·列表-->
      <!--======================================================================================================-->
      <div class="list_wrap">
        <div class="left-list WholeScroll">
          <div class="text-class" v-for="(item, index) in leftList" :key="index" :class="{ 'activecss-left': index == leftListIndex }" @click="(leftListIndex = index), (nowLeftId = item.id), getList(item),chooseMonth = item.name">
            {{item.name}}
          </div>
        </div>
        <div class="scroll-table-array WholeScroll">
          <el-table class="project-management-info1" :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="listOne" :height="tableHeight" @cell-click="cellClick" :summary-method="getSummaries" show-summary tooltip-effect="dark" style="width: 100%;font-family: PingFangSC-Regular;font-size: 14px;">
            <el-table-column label="序号" fixed="left" width="60">
              <template slot-scope="scope">
                <div style="text-align: center;">{{ scope.$index+1 }}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="项目名称" width="350" fixed prop="projectName">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="建设内容及规模" width="350" prop="content">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="建设性质" width="100" prop="ment">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="总投资" width="160" prop="tolInvestment">
              <template slot-scope="scope">
                <div style="text-align: right;">{{ scope.row.tolInvestment }}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="建设地点" width="200" prop="address">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="计划开竣工时间" width="170" prop="startEndTime">
            </el-table-column>

            <el-table-column show-overflow-tooltip :label="`${search.year-1}年底累计完成投资`" width="120" prop="yearEndInvestment">
              <template slot-scope='scope'>
                {{scope.row.yearEndInvestment}}
              </template>
            </el-table-column>

            <el-table-column :label="`${search.year}年计划`" align="center">
              <el-table-column show-overflow-tooltip label="投资额" width="100" prop="investment">
                <template slot-scope="scope">
                  <div style="text-align: right;">{{scope.row.investment}}</div>
                </template>
              </el-table-column>

              <el-table-column show-overflow-tooltip label="当年底形象进度" width="140" prop="futureProgress">
                <template slot-scope='scope'>
                  {{scope.row.futureProgress}}
                </template>
              </el-table-column>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="目前进度" width="100" prop="currentProgress">
              <template slot-scope="scope">
                <div style="text-align: right;">{{scope.row.currentProgress}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="上月完成情况" width="120" prop="lastMonthFinish">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="计划完成产值" width="120" prop="planFinishValue">
              <template slot-scope="scope">
                <div style="text-align: right;">{{scope.row.planFinishValue}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="实际完成产值" width="120" prop="actualFinishValue">
              <template slot-scope="scope">
                <div style="text-align: right;">{{scope.row.actualFinishValue}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="累计完成进度" width="120" prop="accumulatedFinishProgress">
              <template slot-scope="scope">
                <div style="text-align: right;">{{scope.row.accumulatedFinishProgress?scope.row.accumulatedFinishProgress+'%':''}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="累计支付比例" width="120" prop="accumulatedPayRate">
              <template slot-scope="scope">
                <div style="text-align: right;">{{scope.row.accumulatedPayRate?scope.row.accumulatedPayRate+'%':''}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="评价结果" width="200" prop="evaluateResult">
              <template slot-scope='scope'>
                <div class="rowA">
                  <div class="dot" :style="{backgroundColor:scope.row.evaluateResult?colorStr[scope.row.evaluateResult]:'transparent'}" @click.stop="onShowDot(scope.row.id)"></div>
                  <div v-show="isShowEditDot==scope.row.id" class="rowA mlr line">
                    <div class="dot mlr" v-for="(val,key) in colorStr" :key="scope.row.id+key" :style="{backgroundColor:val}" @click.stop="onSelect(scope.row,key)"></div>
                  </div>
                </div>
              </template>
            </el-table-column>

            <!--  -->
            <el-table-column show-overflow-tooltip label="操作" width="100" prop="action" fixed="right">
              <template slot-scope="scope">
                <!-- <el-button size="mini" class="menu_icon iconfont icon-icon_look action_color1" v-permission="permission.show" @click="handleClickDeal({type:'show',name:'查看',detailId:scope.row.id})">&nbsp;查看</el-button> -->
                <!-- <el-button size="mini" class="menu_icon iconfont icon-xiugai-copy action_color1" v-permission="permission.edit" @click="handleClickDeal({type:'update',name:'修改',detailId:scope.row.id})">&nbsp;修改</el-button> -->
                <el-button size="mini" class="menu_icon iconfont icon-shanchu action_color2" v-permission="permission.del" @click="handleClickDeal({type:'delete',name:'删除',detailId:scope.row.id})">&nbsp;删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>
  </div>
</template>

<script>
import { tableRowStyleGol, tableCellStyleGol, tableHeaderCellStyleGol, doCreateObject, } from '@/utils/publicFun'
import * as XLSX from 'xlsx-js-style'
import msgUtil from '@/utils/msgUtil'
import fileOpe from '@/api/file.js'
import { Base64 } from "js-base64";
export default {
  name: `monthlyreport`,
  components: {
    Detail: require('./monthlyreport-detail').default,
  },
  data() {
    return {
      chooseMonth: '1月',
      permission: {
        add: ['100', '1001039:add'],
        edit: ['100', '1001039:edit'],
        del: ['100', '1001039:del'],
        show: ['100', '1001039:show'],
      },
      colorStr: {
        1: '#75ff52',
        2: '#ffe852',
        3: '#ff3e3e'
      },
      isShowEditDot: '',
      newRowName: '',
      tabClickIndex: '',
      tabClickLabel: '',
      addsdId: '', //隧道的id
      //constructionUnitOptions:[], // 公司
      projectOptions: [], // 项目
      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      year: '2023',
      showYearState: false,
      addRowDialog: false,
      hasAdd: false,
      nowLeftId: `${(new Date()).getMonth() + 1}`,
      leftListIndex: (new Date()).getMonth(),
      listOne: [],
      inputValue: '',
      imageProgressInfoListCopy: [],
      leftList: [
        { id: "1", name: "1月" },
        { id: "2", name: "2月" },
        { id: "3", name: "3月" },
        { id: "4", name: "4月" },
        { id: "5", name: "5月" },
        { id: "6", name: "6月" },
        { id: "7", name: "7月" },
        { id: "8", name: "8月" },
        { id: "9", name: "9月" },
        { id: "10", name: "10月" },
        { id: "11", name: "11月" },
        { id: "12", name: "12月" },
      ],
      // 搜索参数
      search: {
        searchName: '',
        pageIndex: 0,
        pageSize: 15,
        pageSum: 0,
        year: '2023',
        month: '1',
      },
      formData: {
        id: '',
        monthLabel: '',
        weekDataId: '',
        weekLabel: '',
        startDateLabel: '',
        endDateLabel: '',
      },
      projectTree: [],
      weekOption: [
        // {
        //   id: '1',
        //   name: '第一周'
        // }
      ],
      // 列类型表
      list: [],
      // 向详情子组件的传值
      postDetailData: {
        show: false,
        type: 'build',
        typeNmae: '新增',
      },
      /**
       * 流程提交数据
       * */
      reportData: {
        //  下一步接收人
        auditorIds: [],
        //  提交，审批意见
        content: '',
        //  被操作表单id
        id: '',
        //  附件表
        fileList: [],
      },

    }
  },
  watch: {
    leftList(val) {
      if (val.length == 0) {
        this.$set(this, 'listOne', [])
      }
    },
    listOne(val) {
      let index = 0
      let arr2 = []
      let deep = function(arr) {
        arr.forEach((item) => {
          item.index = index
          arr2.push(JSON.parse(JSON.stringify(item)))
          index++
          if (item.hasOwnProperty('children')) {
            deep(item.children)
          }
        })
      }
      deep(val)
      console.log('change')
      this.imageProgressInfoListCopy = JSON.parse(JSON.stringify(arr2))
    }
  },
  mounted() {
    this.getList()
  },
  computed: {
    tableHeight: function() {
      return (window.innerHeight - 250) + 'px';
    }
  },

  updated() {
    this.$nextTick(() => {
      this.$refs.multipleTable.doLayout();
    });
  },
  methods: {
    //
    exportByDateOld() {
      let headerDom = document.querySelector('.el-table__header')
      let bodyDom = document.querySelector('.el-table__body')
      let footerDom = document.querySelector('.el-table__footer')
      var WorkSheet = XLSX.utils.table_to_sheet(headerDom)
      var bodySheet = XLSX.utils.table_to_sheet(bodyDom)
      var footerSheet = XLSX.utils.table_to_sheet(footerDom)

      for (let key in bodySheet) {
        let r = key.match(/\d+/)
        if (r !== null && r.length > 0) {
          let rowNum = r[0]
          let cache = bodySheet[key]
          let desc = key.replace(rowNum, '')
          WorkSheet[`${desc}${Number(rowNum) + 2}`] = cache
        }
        if (key.indexOf("W") != -1) {
          delete WorkSheet[key]
        }
      }

      for (let key in footerSheet) {
        let r = key.match(/\d+/)
        if (r !== null && r.length > 0) {
          let rowNum = r[0]
          let cache = footerSheet[key]
          let desc = key.replace(rowNum, '')
          console.log(rowNum)
          console.log(this.list.length)
          WorkSheet[`${desc}${(Number(rowNum) + 2 + this.listOne.length)}`] = cache
        }
      }

      for (let key in WorkSheet) {
        // 去掉操作列
        if (key.indexOf("W") != -1) {
          delete WorkSheet[key]
        }
      }

      let hs = 3 + this.listOne.length;
      let zmhs = 'X' + hs;
      let zgzmhs = 'A1:' + zmhs

      WorkSheet['!ref'] = zgzmhs
      WorkSheet['!fullref'] = zgzmhs
      let new_workbook = XLSX.utils.book_new()
      XLSX.utils.book_append_sheet(new_workbook, WorkSheet, 'Sheet1')
      let fileName = '' + this.search.year + '-' + this.nowLeftId + '月报表.xlsx'
      XLSX.writeFile(new_workbook, fileName)
    },

    priviewReport() {
      let postData = {
        yearMonthStr: `${this.search.year}-${Number(this.nowLeftId) < 10 ? '0' + Number(this.nowLeftId) : Number(this.nowLeftId)}`
      }
      this.$httpPost('buss/investmentProgressSummary/exportSummaryReport', postData).then(res => {
        this.$httpGet('/file-server/file/preview?id=' + res.pdfId).then(response => {
          //  如果是minio地址路径，则调用kkview
          if (!response.data.startsWith("/")) {
            window.open(PREVIEW_URL + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(response.data)));
          } else {
            //  如果是转换后的previewGetFile，浏览器直接打开
            window.open(response.data);
          }
        }).catch(res => {
          msgUtil.error2("预览失败");
        })
      }).catch(e => {
        msgUtil.error2("预览失败");
      })
    },
    // 导出4
    exportByDate() {
      let fileName = '' + this.search.year + '-' + this.nowLeftId + '投资进度汇总表.xls'
      let postData = {
        yearMonthStr: `${this.search.year}-${Number(this.nowLeftId) < 10 ? '0' + Number(this.nowLeftId) : Number(this.nowLeftId)}`
      }
      this.$httpPost('buss/investmentProgressSummary/exportReport', postData,{ responseType: 'blob' }).then(res => {
        doCreateObject(res, fileName)
        // fileOpe.download(res.fileId).then(res => {
        //   doCreateObject(res, fileName);
        //   msgUtil.success2("导出成功")
        // }).catch(res => {
        //   msgUtil.error2("导出失败");
        // })
      }).catch(e => {
        console.log(e);
      })
    },


    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (['tolInvestment','investment'].indexOf(column.property) !== -1) {
          //普通累加
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] += '';
          } else {
            sums[index] = '';
          }
        }
        // else if (column.property == 'completinvestmentYearPer' || column.property == 'accumulatedInvestmentPer' || column.property == 'completinvestmentHalfYearPer' || column.property == 'investmentcompletMonthPer') {
        //   // 单元格 比例是上一个除以上上一个
        //   if (sums[index - 2] == 0) {
        //     sums[index] = ''
        //   } else {
        //     sums[index] = String(((sums[index - 1] / sums[index - 2]) * 100).toFixed(2));
        //   }
        // }
        // else if (column.property == 'investmentcompletMonthDiffe') {
        //   // 单元格 比例是上上一个减去上上上一个
        //   sums[index] = sums[index - 2] - sums[index - 3]
        // }
        else {
          //不需要合计的单元格
          sums[index] = ' ';
        }
      });
      this.$forceUpdate()
      // console.log(sums, 'sumssumssumssumssumssums')
      return sums;
    },
    getList(val) {
      let month = Number(this.nowLeftId) < 10 ? '0' + this.nowLeftId : this.nowLeftId
      let postData = {
        yearMonthStr: `${this.search.year}-${month}`
      }
      this.$httpPost('buss/investmentProgressSummary/getSummaryList', postData).then((res) => {
        let { code, data, msg } = res
        if (code == 200) {
          this.listOne = data;
        } else {
          msgUtil.error2(msg)
        }
      }).catch(() => {
        msgUtil.error2("获取项目标段树失败")
      })
    },

    writeReport() {
      this.postDetailData = {
        show: true,
        type: 'build',
        typeName: '新增',
        detailId: '',
      }
    },
    // 点击单元格
    clickRowspan(row, key) {
      this.$set(row, `isEdit_${key}`, true)
    },
    // 显示详情弹窗 不同状态
    showDetailDialog(flag, params) {
      console.log(flag, params)
      if (!params) {
        params = {}
      }
      params.contractId = this.search.contractId
      switch (flag) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: 'build',
            typeName: '新增',
            params: params,
          }
          break
        case 'update':
          this.postDetailData = {
            show: true,
            type: 'edit',
            typeName: '编辑',
            params: params,
          }
          break
        case 'show':
          this.postDetailData = {
            show: true,
            type: 'check',
            typeName: '查看',
            params: params,
            isAudit: flag,
          }
          break
        case 'audit':
          this.postDetailData = {
            show: true,
            type: 'approve',
            typeName: '审批',
            params: params,
            isAudit: flag,
          }
          break
        case 'history':
          this.postDetailData = {
            show: true,
            type: 'history',
            typeName: '历史',
            params: params,
          }
          break
        case 'approve':
          this.postDetailData = {
            show: true,
            type: 'approve',
            typeName: '审批',
            params: params,
          }
          break
      }
    },
    // 列表的操作流程
    handleClickDeal(res, entity) {
      let that = this
      let type = res.type
      let detailId = res.detailId
      let url = res.url
      let name = res.name
      let actions = res.actions
      // console.log(res)
      switch (type) {
        // 修改
        case 'update':
          // 显示详情弹窗
          this.showDetailDialog(type, {
            detailId: detailId,
            actions: actions,
          })
          break
        // 查看
        case 'show':
        case 'audit':
          // 显示详情弹窗
          this.showDetailDialog(type, {
            detailId: detailId,
            actions: actions,
            params: entity,
          })
          break
        // 上报、重新上报
        case 'report':
          this.$confirm('是否上报?', '提示', {
            confirmButtonClass: 'iconfont icon-icon_ok',
            cancelButtonClass: 'iconfont icon-icon_cancel',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
          })
            .then(() => {
              this.reportData.id = detailId
              this.reportData.auditorIds = entity.reportAuditUserId.split(',')
              this.sealDealHttp(url, '', this.reportData, () => {
                this.$messageSuccess('上报成功!')
              })
            })
            .catch(() => {
              console.log('请求出现错误')
            })

          break
        // 撤回上报
        case 'revokeReport':
          this.$prompt('撤回理由', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          })
            .then(({ value }) => {
              if (value === null || value === '') {
                this.$messageError('请填写撤回理由后重试')
                return
              }
              this.sealDealHttp(
                url,
                `?id=${detailId}&description=${value}`,
                () => {
                  this.$messageSuccess('撤回成功！')
                }
              )
            })
            .catch(() => {
              console.log('请求出现错误')
            })
          break
        // 删除
        case 'delete':
          if (detailId === '') {
            this.$messageError('请先选择要删除的记录！')
            return
          }
          this.$confirm('确定是否删除？', '提示', {
            confirmButtonClass: 'iconfont icon-icon_ok',
            cancelButtonClass: 'iconfont icon-icon_cancel',
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info',
          })
            .then(() => {
              this.sealDealHttp(`/buss/investmentProgressSummary/del`, ``, {
                ids: detailId.split(','),
              }, () => {
                this.$messageSuccess('删除成功!')
              })
            })
          /*.catch(() => {
            console.log('请求出现错误')
          })*/
          break
        // 同意
        case 'agree':
          // 显示详情弹窗
          this.showDetailDialog('approve', {
            detailId: detailId,
            actions: actions,
          })
          break
        // 驳回
        case 'reject':
          this.$prompt('请输入驳回审批意见', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          })
            .then(({ value }) => {
              this.sealDealHttp(
                url,
                `?id=${detailId}&description=${value}`,
                () => {
                  this.$messageSuccess('驳回审批成功!')
                }
              )
            })
            .catch(() => {
              console.log('请求出现错误')
            })
          break
      }
    },


    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      this.$httpPost(url + query, param)
        .then((res) => {
          if (res.code === 200) {
            if (callback) callback(res)
            // 重新获取数据
            setTimeout(() => {
              this.getList(true)
            }, 1000)
          } else {
            this.$messageError(res.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },
    onShowDot(val) {
      if (!this.isShowEditDot || this.isShowEditDot !== val) {
        this.isShowEditDot = val
      } else {
        this.isShowEditDot = ''
      }
    },
    onSelect(item, key) {
      item.evaluateResult = Number(key)
      this.$httpPost('buss/investmentProgressSummary/edit', item).then(res => {
        let { code, msg } = res
        if (code == 200) {
          this.isShowEditDot = ''
          this.getDetail()
        } else {
          this.$messageError(msg)
        }
      })
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      console.log(column)
      if (column.property === 'fillinDateStr') {
        this.showDialog('check', '查看', row.id)
      }
    },
  },
}
</script>

<style scoped lang="scss">
.operate_wrap {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 40px;
  width: 100%;
  box-sizing: border-box;
  .el-button,
  .el-select,
  .el-input {
    border-radius: 4px;
    font-family: PingFangSC-Medium;
    font-size: 14px;
    display: inline-block;
  }
  .el-date-editor--daterange {
    width: 300px;
  }
  .add {
    width: 88px;
  }
  .push {
    background-color: rgb(277, 124, 42);
    border: none;
  }
  .delete {
    margin: 0 10px;
  }
  .search {
    width: 88px;
    float: right;
    color: #fff;
    margin-left: 10px;
  }
  .el-select {
    width: 240px;
    margin-left: 10px;
  }
  .input {
    width: 240px;
    float: right;
    margin-left: 10px;
    color: #3e556e;
  }
}

.flex {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.flex-center {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.list_wrap {
  margin-top: 20px;
  display: flex;
  // height: calc(100vh - 215px);
  // height: 100%;
  .left-list {
    width: 80px;
    padding: 10px 5px;

    background-color: rgba(255, 255, 255, 0.4);
    border: 1px solid #e2e8ec;
    .text-class {
      cursor: pointer;
      font-size: 16px;
      color: #444;
      margin: 5px auto;
      text-align: center;
      padding: 10px 0;
    }
    .activecss-left {
      background-color: #005fff;
      color: #fff !important;
    }
  }
  .scroll-table-array {
    // height: calc(100% - 130px) !important;
    height: 100%;
    overflow-y: auto;
    width: 100%;
    .engincontentNameTitleCss {
      font-size: 14px;
      font-weight: bold;
    }
    .engincontentNameChildCss {
      font-size: 14px;
      // font-weight: bold;
      padding-left: 20px;
    }
    .iconBox {
      i {
        cursor: pointer;
      }
    }
  }
}
.edit-box {
  display: flex;
  align-items: center;
}
.btnGroupAA {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
  width: 80px;
  padding: 0px;
  .btn-item {
    flex: 1;
    cursor: pointer;
  }
}
.rowA {
  display: flex;
  align-items: center;
}
.dot {
  width: 20px;
  height: 20px;
  border-radius: 50% 50%;
  cursor: pointer;
}
.mlr {
  margin: 0 10px;
}
.line {
  border: 1px solid #ebeef5;
  border-radius: 15px;
  padding: 5px;
}
.dropdown {
  display: flex;
  align-items: center;
}
</style>
<style lang="scss">
.btnGroupAAUnit {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  .el-input-group__append {
    padding: 0 !important;
  }
}
</style>
